package com.zy.garbage.controller;

import com.zy.garbage.enums.PermsEnum;
import com.zy.garbage.enums.ResultEnum;
import com.zy.garbage.exception.CommonException;
import com.zy.garbage.form.CreateGarbageForm;
import com.zy.garbage.form.SortForm;
import com.zy.garbage.service.SortService;
import com.zy.garbage.util.ResultUtil;
import com.zy.garbage.vo.GarbageVO;
import com.zy.garbage.vo.QuestionStatisticVO;
import com.zy.garbage.vo.ResultVO;
import com.zy.garbage.vo.SortVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/sort")
public class SortController extends BaseController {

    @Autowired
    private SortService sortService;

    @GetMapping("/showAll")
    public ResultVO showAll() {
//        if (claims.get("perms").equals(PermsEnum.ADMIN.getPerms())) {
            try {
                List<SortVO> sortVOList = sortService.findAll();
                return ResultUtil.success(sortVOList);
            } catch (CommonException e) {
                throw new CommonException(e.getCode(), e.getMessage());
            }
//        }
//        throw new CommonException(ResultEnum.NO_PERMS);
    }

    @PostMapping("/create")
    public ResultVO create(@Validated @RequestBody SortForm sortForm, HttpServletResponse response) {
        if (claims.get("perms").equals(PermsEnum.ADMIN.getPerms())) {
            try {
                SortVO sortVO = sortService.save(sortForm);
                return ResultUtil.success(sortVO);
            } catch (CommonException e) {
                throw new CommonException(e.getCode(), e.getMessage());
            }
        }
        throw new CommonException(ResultEnum.NO_PERMS);
    }

    @PutMapping("/update")
    public ResultVO update(@Validated @RequestBody SortForm sortForm, HttpServletResponse response) {
        if (claims.get("perms").equals(PermsEnum.ADMIN.getPerms())) {
            try {
                SortVO sortVO = sortService.update(sortForm);
                return ResultUtil.success(sortVO);
            } catch (CommonException e) {
                throw new CommonException(e.getCode(), e.getMessage());
            }
        }
        throw new CommonException(ResultEnum.NO_PERMS);
    }

    @DeleteMapping("/delete/{sortId}")
    public ResultVO delete(@PathVariable("sortId") Integer sortId, HttpServletResponse response) {
        if (claims.get("perms").equals(PermsEnum.ADMIN.getPerms())) {
            try {
                sortService.delete(sortId);
                return ResultUtil.success(null);
            } catch (CommonException e) {
                throw new CommonException(e.getCode(), e.getMessage());
            }
        }
        throw new CommonException(ResultEnum.NO_PERMS);
    }
}
